import categoryApi from '@/api/shop/category'
import attrKeyApi from '@/api/shop/attrKey'
import attrValApi from '@/api/shop/attrVal'
import { getToken } from '@/utils/auth'
import { getApiUrl } from '@/utils/utils'
import { Loading } from 'element-ui'
import permission from '@/directive/permission/index.js'
export default {
  directives: { permission },
  data() {
    return {
      imgDialogVisible: undefined,
      uploadUrl: '',
      uploadFileId: '',
      uploadHeaders: {
        'Authorization': ''
      },
      loadingInstance: {},
      formVisible: false,
      formTitle: '添加二级分类',
      isAdd: true,
      form: {
        id: '',
        name: '',
        url: '',
        icon: '',
        fistId: undefined,
        firstName: undefined,

      },
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        parentId: undefined,
      },
      total: 0,
      list: [],
      listLoading: true,
      selRow: {},
      apiUrl: getApiUrl(),
      banner: {
        idCategory: '',
        activeName: 'first',
        visible: false,
        list: []
      },
      attrKey: {
        idCategory: '',
        visible: false,
        list: []
      },
      attrVal: {
        idAttrKey: '',
        visible: false,
        list: []
      },
      primaryClassificationOption: [{
        "label": "所有分类",
        "value": 0,
      }],
      tmpOptions: {},
    }

  },
  watch: {
    listQueryParentId(val, oldVal) {
      //console.log('筛选框值变动', val, oldVal);
      if (val == 0) {
        this.listQuery.parentId = ''
      } else {
        this.listQuery.parentId = val
      }
      this.fetchData()
    }
  },
  computed: {
    listQueryParentId() {
      return this.listQuery.parentId
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.uploadUrl = getApiUrl() + '/file'
      this.uploadHeaders['Authorization'] = getToken()
      categoryApi.getOpenFirstCategory().then(response => {
        this.tmpOptions = response.data
        for (let index = 0; index < this.tmpOptions.length; index++) {
          const e = this.tmpOptions[index];
          this.primaryClassificationOption.push({ "label": e.name, "value": e.id })
        }
      })
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      if (this.listQuery.parentId == null || this.listQuery.parentId == 0) {
        categoryApi.findByFirstId({
          id: '',
          page: this.listQuery.page,
          limit: this.listQuery.limit,
        }).then(response => {
          //console.log("筛选全部一级分类,返回数据", response);
          this.list = []
          let tList = response.data
          for (let i = 0; i < tList.length; i++) {
            const e = tList[i];
            let t = {
              id: e.id,
              fistId: e.fistId,
              icon: e.icon,
              name: e.name,
              categoryFirst: e.categoryFirst,
            }
            this.list.push(t)
          }
          this.listLoading = false
          this.total = response.data.total
        })
      } else {
        categoryApi.findByFirstId({
          id: this.listQuery.parentId,
          page: this.listQuery.page,
          limit: this.listQuery.limit,
        }).then(response => {
          this.list = []
          //console.log("筛选具体一级分类，返回数据", response);
          let tList = response.data
          for (let i = 0; i < tList.length; i++) {
            const e = tList[i];
            let t = {
              id: e.id,
              fistId: e.fistId,
              icon: e.icon,
              name: e.name,
              categoryFirst: e.categoryFirst,
            }
            this.list.push(t)
          }
          this.listLoading = false
          this.total = response.data.total
        })
      }
    },
    search() {
      this.listQuery.page = 1
      this.fetchData()
    },
    reset() {
      this.listQuery.id = ''
      this.listQuery.page = 1
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleClose() {

    },
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1
      this.fetchData()
    },
    fetchPage(page) {
      this.listQuery.page = page
      this.fetchData()
    },
    changeSize(limit) {
      this.listQuery.limit = limit
      this.fetchData()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      //console.log('处理当前变化', currentRow);
      this.selRow = currentRow
    },
    add() {
      this.formTitle = '添加二级分类'
      this.formVisible = true
      this.isAdd = true
    },
    save() {
      if (this.isAdd) {
        //console.log('触发新增');
        if (this.form.name != ''
          && this.form.icon != '') {
          //console.log('新增数据', this.form);
          categoryApi.save({
            name: this.form.name,
            icon: this.form.icon,
            fistId: this.form.fistId,
            categoryFirst: this.form.categoryFirst,
          }).then(response => {
            this.$message({
              message: this.$t('common.optionSuccess'),
              type: 'success'
            })
            this.fetchData()
            this.formVisible = false
          })
        } else {
          this.$message({
            message: '请输入必要的信息',
            type: 'error'
          })
          return false
        }
      } else {
        //console.log('触发修改');
        this.toUpdate()
      }
    },
    toUpdate() {
      if (this.form.name != '' &&
        this.form.icon != '') {
        //console.log('更新数据', this.form);
        categoryApi.save({
          id: this.form.id,
          name: this.form.name,
          icon: this.form.icon,
          fistId: this.form.fistId
        }).then(response => {
          this.$message({
            message: this.$t('common.optionSuccess'),
            type: 'success'
          })
          this.fetchData()
          this.formVisible = false
        })
      } else {
        this.$message({
          message: '请输入必要的信息',
          type: 'error'
        })
        return false
      }
    },
    firstIdHaveChange() {
      //console.log('所属一级分类变动',this.form.fistId);
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true
      }
      this.$message({
        message: this.$t('common.mustSelectOne'),
        type: 'warning'
      })
      return false
    },
    edit() {
      if (this.checkSel()) {
        this.isAdd = false
        //console.log(111, this.selRow)
        this.form.id = this.selRow.id
        this.form.fistId = this.selRow.categoryFirst.id
        this.form.firstName = this.selRow.categoryFirst.name
        this.form.icon = this.selRow.icon
        this.form.name = this.selRow.name
        this.formTitle = '编辑二级分类'
        this.formVisible = true
      }
    },
    clickRow(row) {
      this.selRow = row
    },
    remove() {
      if (this.checkSel()) {
        var id = this.selRow.id
        this.$confirm(this.$t('common.deleteConfirm'), this.$t('common.tooltip'), {
          confirmButtonText: this.$t('button.submit'),
          cancelButtonText: this.$t('button.cancel'),
          type: 'warning'
        }).then(() => {
          categoryApi.remove(id).then(response => {
            this.$message({
              message: this.$t('common.optionSuccess'),
              type: 'success'
            })
            this.fetchData()
          }).catch(err => {

          })
        }).catch(() => {
        })
      }
    },
    bannerMgr(idCategory) {
      this.banner.visible = true
      this.banner.idCategory = idCategory
      categoryApi.getBanners(idCategory).then(response => {
        this.banner.list = response.data
        //console.log('banner', this.banner)
      })
    },
    bannerRemove(id) {
      categoryApi.removeBanner(this.banner.idCategory, id).then(response => {
        this.$message({
          message: this.$t('common.optionSuccess'),
          type: 'success'
        })
        this.bannerMgr(this.banner.idCategory)
      })

    },
    bannerEdit() {
    },
    addBanner() {
      this.$router.push({ path: 'banner', query: { idCategory: this.banner.idCategory } })
    },
    attrKeyMgr(idCategory) {
      this.attrKey.visible = true
      this.attrKey.idCategory = idCategory
      categoryApi.getAttrKeys(idCategory).then(response => {
        this.attrKey.list = response.data
      })
    },
    attrKeyAdd() {
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        attrKeyApi.save({ attrName: value, idCategory: this.attrKey.idCategory }).then(response => {
          this.$message({
            type: 'success',
            message: '新增属性成功'
          })
          categoryApi.getAttrKeys(this.attrKey.idCategory).then(response2 => {
            this.attrKey.list = response2.data
          })

        })

      })
    },
    attrKeyEdit(item) {
      //console.log('item', item)
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.attrName,
      }).then(({ value }) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        attrKeyApi.updateAttrName(item.id, value).then(response => {
          item.attrName = value
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
        })
        return

      })

    },
    attrKeyRemove(id) {
      //console.log('id', id)
      attrKeyApi.remove(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        categoryApi.getAttrKeys(this.attrKey.idCategory).then(response2 => {
          this.attrKey.list = response2.data
        })
      })

    },
    openAttrValDialog(item) {
      this.attrVal.idAttrKey = item.id
      this.attrVal.visible = true
      //console.log('item', item)
      attrValApi.getAttrVals(this.attrVal.idAttrKey).then(response2 => {
        this.attrVal.list = response2.data
      })
    },
    attrValAdd() {
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        attrValApi.save({ attrVal: value, idAttrKey: this.attrVal.idAttrKey }).then(response => {
          this.$message({
            type: 'success',
            message: '新增属性成功'
          })
          attrValApi.getAttrVals(this.attrVal.idAttrKey).then(response2 => {
            this.attrVal.list = response2.data
          })

        })

      })
    },
    attrValEdit(item) {
      //console.log('item', item)
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.attrVal,
      }).then(({ value }) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        attrValApi.updateAttrVal(item.id, value).then(response => {
          item.attrName = value
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
          attrValApi.getAttrVals(this.attrVal.idAttrKey).then(response2 => {
            this.attrVal.list = response2.data
          })
        })
        return

      })

    },
    attrValRemove(id) {
      //console.log('id', id)
      attrValApi.remove(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        attrValApi.getAttrVals(this.attrVal.idAttrKey).then(response2 => {
          this.attrVal.list = response2.data
        })
      })

    },
    selectClassification() {
      //console.log(1234)
      //console.log(this.classificationSelector)
    },
    handleBeforeUpload() {
      if (this.uploadFileId !== '') {
        this.$message({
          message: this.$t('common.mustSelectOne'),
          type: 'warning'
        })
        return false
      }
      this.loadingInstance = Loading.service({
        lock: true,
        text: this.$t('common.uploading'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    handleUploadSuccess(response, raw) {
      this.loadingInstance.close()
      if (response.code === 20000) {
        this.uploadFileId = response.data.realFileName
        this.form.icon = response.data.realFileName
        this.imgDialogVisible = true
      } else {
        this.$message({
          message: this.$t('common.uploadError'),
          type: 'error'
        })
      }
    }

  }
}
